package com.zxp.web.config.springSecurity.detailService;

import com.zxp.web.config.springSecurity.exeptions.CustomAuthenionException;
import com.zxp.web.constants.Constants;
import com.zxp.web.sys_menu.entity.SysMenu;
import com.zxp.web.sys_menu.service.SysMenuService;
import com.zxp.web.sys_user.entity.SysUser;
import com.zxp.web.sys_user.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author MasterZ
 * @Date 2025/10/7 14:51
 */
@Component
public class CustomerUserDetailService implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.loadUser(username);
        if (user == null) {
            throw new CustomAuthenionException("用户名错误！");
        }
        List<SysMenu> menus;
        List<GrantedAuthority> authorityList = new ArrayList<>(List.of());
        //是否超级管理员
        if (StringUtils.isNotEmpty(user.getIsAdmin()) && Constants.IS_ADMIN.equals(user.getIsAdmin())) {
            menus = sysMenuService.list();
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else {
            menus = sysMenuService.getMenuByUserId(user.getUserId());
            authorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        //获取菜单表里的权限字符code
        List<String> codeList = Optional.ofNullable(menus).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null && StringUtils.isNotEmpty(item.getCode()))
                .map(SysMenu::getCode)
                .toList();
        String[] permissions = codeList.toArray(new String[0]);
        authorityList.addAll(AuthorityUtils.createAuthorityList(permissions));
        user.setAuthorities(authorityList);
        return user;
    }
}